package com.skeyedu.dao;

import cn.hutool.core.util.ObjectUtil;
import com.skeyedu.pojo.Users;
import com.skeyedu.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Description 描述
 * @Author 羽落陌殇
 * @Date 2021/7/22 16:21
 * @Version 1.0.0
 */
public class UserDaoImpl implements UserDao {
    @Override
    public int createUser(Users users) throws SQLException {
        String sql = "insert into users values(?,?,?,?,?)";
        Object[] params = {users.getId(), users.getUsername(),
                users.getEmail(), users.getPassword(),users.getStatus()};
        Connection connection = DBUtils.getConnection();
        PreparedStatement preparedStatement = null;
        int result = 0;
        if (ObjectUtil.isNotNull(connection)) {
            result = DBUtils.executeUpdate(connection, preparedStatement, sql, params);
        }
        return result;
    }

    @Override
    public int updateUserStatus(int status, String id) throws SQLException {
        String sql = "update users set status = ? where id = ?";
        Object[] params = {status, id};
        Connection connection = DBUtils.getConnection();
        PreparedStatement preparedStatement = null;
        int result = 0;
        if (ObjectUtil.isNotNull(connection)) {
            result = DBUtils.executeUpdate(connection, preparedStatement, sql, params);
        }
        return result;
    }

    @Override
    public Users getLoginUser(String username, String password) throws SQLException {
        String sql = "select * from users where status = 1 and username = ? and password = ?";
        Object[] params = {username, password};
        Connection connection = DBUtils.getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Users users = null;
        if (ObjectUtil.isNotNull(connection)) {
            resultSet = DBUtils.executeQuery(connection, preparedStatement, resultSet, sql, params);
        }
        if (resultSet.next()) {
            users = new Users();
            users.setId(resultSet.getString("id"));
            users.setUsername(resultSet.getString("username"));
            users.setEmail(resultSet.getString("email"));
            users.setPassword(resultSet.getString("password"));
            users.setStatus(resultSet.getInt("status"));
        }
        return users;
    }
}
